﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;

namespace DATN.Common
{
   public static class Utility
    {
        public static string ToStringOrDefault(this object value)
        {
            if (value == null || DBNull.Value == value) return string.Empty;
            return value.ToString();
        }

        public static int ToNumeric(this object value)
        {
            try
            {
                return Int32.Parse(value.ToStringOrDefault(), CultureInfo.CurrentCulture);
            }
            catch (OverflowException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (FormatException e)
            {
                Console.WriteLine(e.ToString());
            }
            return 0;
        }

        /// <summary>
        /// MD5 Hash generator
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static String GetMD5(String strSource)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(strSource);
            bs = x.ComputeHash(bs);
            var s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2", CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentCulture));
            }
            return s.ToString();
        }

        /// <summary>
        /// Check Valid Email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsValidEmail(string email)
        {
            if (!string.IsNullOrEmpty(email))
            {
                var emailregex = new Regex("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
                var m = emailregex.Match(email);
                return m.Success;
            }
            return false;
        }

        /// <summary>
        /// Send Email New Password
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static bool SendEmail(string from, string to, string subject, string body)
        {
            if (!string.IsNullOrEmpty(from)
                && !string.IsNullOrEmpty(to)
                && !string.IsNullOrEmpty(subject)
                && !string.IsNullOrEmpty(body))
            {
                try
                {

                
                var smtp = new SmtpClient();
                var msg = new MailMessage(from, to, subject, body);
                msg.IsBodyHtml = true;
                //SmtpClient smtpClient = new SmtpClient();
                smtp.EnableSsl = true;
                //smtp.Host = "smtp.gmail.com";//Sử dụng SMTP của gmail
                smtp.Send(msg);
                return true;
                }
                catch
                {
                }
            }
            return false;
        }

        /// <summary>
        /// Gets the get password.
        /// </summary>
        /// <value>
        /// The get password.
        /// </value>
        public static string CreatePassword()
        {

            var builder = new StringBuilder();
            builder.Append(RandomString(4, true));
            builder.Append(RandomNumber(1000, 9999));
            builder.Append(RandomString(2, false));
            return builder.ToString();

        }

        /// <summary>
        /// Randoms the string.
        /// </summary>
        /// <param name="size">The size.</param>
        /// <param name="lowercase">if set to <c>true</c> [lowercase].</param>
        /// <returns></returns>
        public static string RandomString(int size, bool lowercase)
        {
            var builder = new StringBuilder();
            var random = new Random();
            for (int i = 0; i < size; i++)
            {
                char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowercase)
                return builder.ToString().ToLower(CultureInfo.CurrentCulture);
            return builder.ToString();
        }

        /// <summary>
        /// Randoms the number.
        /// </summary>
        /// <param name="min">The min.</param>
        /// <param name="max">The max.</param>
        /// <returns></returns>
        public static int RandomNumber(int min, int max)
        {
            var random = new Random();
            return random.Next(min, max);
        }

        /// <summary>
        /// Lấy ra thứ tự trong năm của tuần có chứa ngày nhập vào 
        /// với Culture mặc định là Culture hiện tại
        /// </summary>
        /// <param name="datetime">Ngày nhập vào</param>
        /// <returns>Trả về kiểu datetime là ngày đầu tuần, int là thứ tự của tuần hiện tại trong năm</returns>
        public static string GetWeekInYear(DateTime datetime, out DateTime FirstDayOfWeek, out int CurrentWeek)
        {
            string txt = "";
            CultureInfo myCI = new CultureInfo(System.Globalization.CultureInfo.CurrentCulture.LCID);//System.Globalization.CultureInfo.CurrentCulture.LCID lay theo he thong
            System.Globalization.Calendar myCal = myCI.Calendar;

            // Gets the DTFI properties required by GetWeekOfYear.
            CalendarWeekRule myCWR = myCI.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;

            // Displays the number of the current week relative to the beginning of the year.
            txt += string.Format("The CalendarWeekRule used for the current culture is {0}.", myCWR);
            txt += "<br>" + string.Format("The FirstDayOfWeek used for the current culture is {0}.", myFirstDOW);
            CurrentWeek = myCal.GetWeekOfYear(datetime, myCWR, myFirstDOW);
            txt += "<br>" + string.Format("Therefore, the current week is Week {0} of the current year.", CurrentWeek);
            FirstDayOfWeek = datetime;
            while (FirstDayOfWeek.DayOfWeek != DayOfWeek.Monday) FirstDayOfWeek = FirstDayOfWeek.AddDays(-1); // tìm đầu tuần
            txt += "<br>" + string.Format("The FirstDayOfWeek  for the current week is {0}.", FirstDayOfWeek.ToString("dd/MM/yyyy"));

            // Displays the total number of weeks in the current year.
            DateTime LastDay = new System.DateTime(datetime.Year, 12, 31);
            txt += "<br>" + string.Format("There are {0} weeks in the current year ({1}).", myCal.GetWeekOfYear(LastDay, myCWR, myFirstDOW), LastDay.Year);
            return txt;
        }
    }
}
